const userApi = require('../../../api/user.js')
Page({
  data: {
    bottomPadding: 0,
    pageSize: 10000,
    pageNum: 1,
    unReadList: [],
    readList: [],
    total: 0
  },
  async onLoad(options) {
    this.setData({ bottomPadding: getApp().globalData.bottomPadding })
    await this.queryUnreadMessage(options)
    await this.queryReadMessage(options)
  },
  async queryUnreadMessage(options) {
    // Todo 后端没有做防重复的操作，所以当前一次性取出来
    let data = { ...options, pageSize: this.data.pageSize, pageNum: this.data.pageNum, isRead: 1 }
    let res = await userApi.listMessage(data)
    this.setData({
      total: res.total,
      unReadList: res.rows?.map((item) => {
        let messageContent
        if (item.messageType === '1') {
          messageContent = '评论了你的文章'
        } else if (item.messageType === '2') {
          messageContent = '点赞了你的文章'
        } else if (item.messageType === '3') {
          messageContent = '回复了你的评论'
        } else if (item.messageType === '4') {
          messageContent = '关注了你'
        }
        return {
          ...item,
          messageContent,
          messageTime: this.hoursAgo(item.messageTime)
        }
      })
    })
  },
  async queryReadMessage(options) {
    // Todo 后端没有做防重复的操作，所以当前一次性取出来
    let data = { ...options, pageSize: this.data.pageSize, pageNum: this.data.pageNum, isRead: 2 }
    let res = await userApi.listMessage(data)
    res.rows.splice(0, this.data.unReadList.length)
    this.setData({
      total: res.total,
      readList: res.rows?.map((item) => {
        let messageContent
        if (item.messageType === '1') {
          messageContent = '评论了你的文章'
        } else if (item.messageType === '2') {
          messageContent = '点赞了你的文章'
        } else if (item.messageType === '3') {
          messageContent = '回复了你的评论'
        } else if (item.messageType === '4') {
          messageContent = '关注了你'
        }
        return {
          ...item,
          messageContent,
          messageTime: this.hoursAgo(item.messageTime)
        }
      })
    })
  },
  hoursAgo(dateString) {
    // 解析字符串为一个日期对象
    let specificTime = new Date(dateString)
    // 获取当前日期
    let today = new Date()
    today.setHours(0, 0, 0, 0) // 将当前日期设置为00:00:00
    // 比较特定日期与当前日期
    if (
      specificTime.toISOString().split('T')[0] !==
      today.toISOString().split('T')[0]
    ) {
      return dateString
    }
    const futureDate = new Date(dateString)
    const now = new Date()
    const timeDifference = futureDate - now
    if (timeDifference > 0) {
      const hoursUntil = timeDifference / (1000 * 60 * 60)
      return Math.trunc(hoursUntil) + `小时后`
    } else {
      const hoursAgo = -timeDifference / (1000 * 60 * 60)
      return Math.trunc(hoursAgo) + `小时前`
    }
  },
  articleClick(e) {
    wx.navigateTo({
      url: `/pages/community/detail/index?articleId=${e.currentTarget.dataset.item.publishId}`
    })
  }
})
